package com.jack.vipmis.vip.jpush.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.DeviceEnum;
import cn.jpush.api.push.MessageResult;
import cn.jpush.api.push.NotificationParams;
import cn.jpush.api.push.ReceiverTypeEnum;

import com.jack.vipmis.common.entity.enums.BooleanEnum;
import com.jack.vipmis.common.web.controller.BaseCRUDController;
import com.jack.vipmis.vip.jpush.entity.PushResources;
import com.jack.vipmis.vip.jpush.service.PushResourcesService;

/**
 * 推送资源管理
 * 
 * @author JackLiang
 * @date 2014-6-25
 * @version 1.0
 */
@Controller
@RequestMapping(value = "/vip/push/resources")
public class PushResourcesController extends BaseCRUDController<PushResources, Long> {

	private static final String	appKey			= "4710055e81bebe8cffc36f99";
	private static final String	masterSecret	= "00379628d21e7647db9f0af7";
	private JPushClient			jpushAndroid	= null;
	private static final String	TAG				= "tag_api";

	private PushResourcesService getPushResourcesService() {
		return (PushResourcesService) baseService;
	}

	public PushResourcesController() {
		setResourceIdentity("vip:pushResources");
	}

	@Override
	protected void setCommonData(Model model) {
		model.addAttribute("booleanList", BooleanEnum.values());
	}

	@Override
	public String create(Model model, PushResources m, BindingResult result, RedirectAttributes redirectAttributes) {
		jpushAndroid = new JPushClient(masterSecret, appKey, 0, DeviceEnum.Android, false);

		if (m != null) {
			jpushAndroid.sendNotificationAll(m.getTitle());
		}
		return super.create(model, m, result, redirectAttributes);
	}

	/**
	 * 发送推送消息
	 */
	@RequestMapping(value = "saveAdPush")
	public void saveAdJpsh(PushResources m) {
		jpushAndroid = new JPushClient(masterSecret, appKey, 0, DeviceEnum.Android, false);
		try {
			if (m != null) {
				getPushResourcesService().save(m);
				MessageResult result = jpushAndroid.sendNotificationAll(m.getTitle());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public int sendNotification(String content) {
		NotificationParams params = new NotificationParams();
		params.setReceiverType(ReceiverTypeEnum.TAG);
		params.setReceiverValue(TAG);
		MessageResult result = jpushAndroid.sendNotification(content, params, null);
		return result.errcode;
	}
}
